<script setup lang="ts">
import type { FormInstance, FormValidateCallback, UploadFiles } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { EaWorkType } from './type'
import { tree2List } from '@/utils/list'
import { buildImgSrc } from '@/utils/file'
import { uploadFile } from '@/api'

const baseApi = '/ea/ea-work-type'

defineProps<{
  // 禁用表单内的所有组件
  disabled?: boolean
  // 禁用属性列表（只读不可输入）
  disabledProps?: string[]
  // 不可见属性列表（忽略不加载）
  invisibleProps?: string[]
}>()

const emit = defineEmits<{
  (e: 'complete', id?: string, isNew?: boolean): void
  (e: 'submitting', submitting: boolean): void
}>()

const { initRelatedData, relatedData } = useOption({
  dict: ['ENABLE_TYPE'],
  load: {
    parentIdOptions: {
      type: 'EaWorkType',
      label: 'title',
      parent: 'parentId',
      parentPath: 'parentIdsPath',
      lazyChild: false
    }
  }
})

const { loadData, loading, model } = useDetail<EaWorkType>(baseApi, {
  parentId: '0',
  isNeed: false,
  suggestedPrice: 50
})
// 文件列表
const image = ref<UploadFiles>([])

// 上传文件
const imageUpload = async options => {
  try {
    const res = await uploadFile(options.file)
    if (res.data) {
      model.value.image = res.data
      ElMessage.success('上传成功')
    }
  } catch (error) {
    ElMessage.error('上传失败')
    // 上传失败时移除文件
    const index = image.value.findIndex(item => item.uid === options.file.uid)
    if (index !== -1) {
      image.value.splice(index, 1)
    }
  }
}

const handleImageFileRemove = (file, fileList) => {
  image.value = fileList.filter(item => item.uid !== file.uid)
  model.value.image = '' // 移除文件时清空表单中的值
}

const { submitting, submit } = useForm({ baseApi, successCallback: (id, isNew) => emit('complete', id, isNew) })
watch(submitting, value => emit('submitting', value))

//  表单
const formRef = ref<FormInstance>()

const currentInstance = getCurrentInstance()

const validate = (
  callback: FormValidateCallback = (valid: boolean) =>
    !valid && ElMessage.error({ message: '表单校验不通过', grouping: true })
) =>
  Promise.all([formRef.value].map(e => e?.validate?.(callback)).filter(e => !!e))
    .then((arr: (boolean | undefined)[]) => arr.every(e => e))
    .catch(() => false)

defineExpose({
  init: (id?: string, refresh = true, initData?: Record<string, unknown>) => {
    // 初始化选项
    initRelatedData()
    if (model.value.id === id && !refresh) return
    // 加载数据
    loadData(id).then(() => {
      if (model.value.image) {
        image.value = [
          {
            name: String(new Date().getTime()),
            url: model.value.image,
            status: 'success',
            uid: Date.now()
          }
        ]
      }
      if (!id) {
        if (initData) {
          Object.keys(initData).forEach(key => (model.value[key as keyof EaWorkType] = initData[key] as any))
        }
      }
    })
  },
  validate,
  getData: async (relatedLabel = false) => {
    console.log('getdata')
    const data: Record<string, unknown> = _.cloneDeep(model.value)
    if (!relatedLabel) return data
    if ((data.parentId as string)?.length) {
      let options = relatedData.parentIdOptions
      options = tree2List(options)
      data.parentIdLabel = options.find(e => e.value === data.parentId)?.label
    } else data.parentIdLabel = undefined
    data.imageFiles = currentInstance?.refs.imageRef?.getFiles()

    data.statusLabel = relatedData.enableTypeOptions.find(e => e.value === data.status)

    return data
  },
  submit: () => {
    console.log(model.value, formRef.value)
    submit(model.value, formRef.value)
  },
  reset: () => {
    formRef.value?.resetFields()
    model.value.id = void 0
    model.value.imageFiles = []
  }
})

const imageUrl = ref('')
</script>

<template>
  <el-form ref="formRef" v-loading="loading" :model="model" label-width="120" :disabled="disabled">
    <el-row :gutter="18">
      <el-col v-if="!invisibleProps?.includes('parentId')" :span="24">
        <el-form-item prop="parentId" label="上级">
          <el-tree-select
            v-model="model.parentId"
            :disabled="disabledProps?.includes('parentId')"
            :data="
              relatedData?.parentIdOptions?.map(e => {
                const { children, ...rest } = e
                return {
                  ...rest
                }
              })
            "
            filterable
            check-strictly
            clearable
          />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('title')" :span="24">
        <el-form-item prop="title" label="分类名" :rules="{ required: true, message: '不能为空', whitespace: true }">
          <el-input v-model="model.title" :disabled="disabledProps?.includes('title')" clearable />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('image')" :span="24">
        <el-form-item prop="image" label="图片">
          <el-upload
            v-model:file-list="image"
            :http-request="imageUpload"
            :on-remove="handleImageFileRemove"
            :limit="1"
            list-type="picture"
          >
            <el-button v-if="!model.image" size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-col>
      <!-- <el-col v-if="!invisibleProps?.includes('image')" :span="24">
        <di-input
          ref="imageRef"
          v-model="model.image"
          :disabled="disabledProps?.includes('image')"
          :file-list="model.imageFiles as FileRecord[]"
          :config="{
            type: 'upload',
            prop: 'image',
            label: '分类图片',
            limit: 1,
            listType: 'picture-card',
            accept: '.jpg,.jpeg,.png,.gif,.bmp'
          }"
          @preview="accessUrl => (imageUrl = accessUrl)"
        />
      </el-col> -->

      <!--    <el-col v-if="!invisibleProps?.includes('status')" :span="24">
        <el-form-item prop="status" label="状态">
          <el-select v-model="model.status" :disabled="disabledProps?.includes('status')" filterable clearable>
            <el-option v-for="item in relatedData.enableTypeOptions" :key="item.value" v-bind="item" />
          </el-select>
        </el-form-item>
      </el-col>-->
      <!--      <el-col v-if="!invisibleProps?.includes('remark')" :span="24">
        <el-form-item prop="remark" label="备注说明">
          <el-input v-model="model.remark" :disabled="disabledProps?.includes('remark')" clearable />
        </el-form-item>
      </el-col>-->
      <!--      <el-col v-if="!invisibleProps?.includes('isNeed')" :span="24">
        <el-form-item prop="isNeed" label="是否需要证件照">
          <el-switch v-model="model.isNeed" :disabled="disabledProps?.includes('isNeed')" />
        </el-form-item>
      </el-col>-->
      <el-col v-if="!invisibleProps?.includes('suggestedPrice')" :span="24">
        <el-form-item prop="suggestedPrice" label="建议价格">
          <el-input-number
            v-model="model.suggestedPrice"
            :disabled="disabledProps?.includes('suggestedPrice')"
            step-strictly
          />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <el-image-viewer v-if="imageUrl" :url-list="[imageUrl]" @close="imageUrl = ''" />
</template>

<style scoped lang="scss">
.option {
  display: flex;
  justify-content: space-between;

  .ext {
    font-size: var(--el-font-size-extra-small);
    color: var(--el-text-color-secondary);
  }
}
</style>
